<template>
  <div>
    <el-dialog
      v-model="show"
      :title="title"
      width="45vw"
      destroy-on-close
      @close="handleCancel"
    >
      <el-form
        :model="formData"
        label-width="120px"
        ref="formDataRef"
        :rules="formRules"
      >
        <el-form-item label="下一步流转至">
          <el-radio-group
            v-if="nextJumpToArr && nextJumpToArr.length"
            v-model="formData.nextJumpObj.nextJumpToId"
          >
            <el-radio
              v-for="item in nextJumpToArr"
              :key="item.id"
              :label="item.id"
              border
              @change="changeNextJump"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>

          <el-input v-else v-model="formData.nextFlowName" disabled></el-input>
        </el-form-item>

        <el-form-item
          v-if="!formData.isLast && !formData.isNoNextHandler"
          label="下一步处理人"
          prop="handlederId"
        >
          <el-select
            v-if="isMultiple"
            v-model="formData.handlederId"
            :disabled="disabledJs"
            style="width: 100%"
            :filterable="!(approveType === '3001' && formData.nextJumpObj.nextJumpToId === 'ACT_021')"
            clearable
            :multiple="!formData.isSingle"
            remote
            placeholder="请输入姓名搜索"
            :remote-method="getUserData"
            value-key="id"
            @change="changeHandleder"
          >
            <el-option
              id="default-option"
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item"
            ></el-option>
          </el-select>
          <el-select
            v-if="!isMultiple"
            v-model="formData.handlederId"
            :disabled="disabledJs"
            style="width: 100%"
            :filterable="!(approveType === '3001' && formData.nextJumpObj.nextJumpToId === 'ACT_021')"
            clearable
            :multiple="formData.isSingle"
            remote
            placeholder="请输入姓名搜索"
            :remote-method="getUserData"
            value-key="id"
            @change="changeHandleder"
          >
            <el-option
              id="default-option"
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- TODO: 发起阶段不显示审批意见栏 -->
        <!-- <el-form-item
          label="审批意见"
          prop="isApprove"
          v-if="!formData.isFirst && !formData.isNoNextApprove"
        >
          <el-radio-group v-model="formData.isApprove">
            <el-radio label="1">同意</el-radio>
            <el-radio label="0">不同意</el-radio>
          </el-radio-group>
        </el-form-item> -->

        <!-- 会签需要上传附件 -->
        <el-form-item label="会签记录" v-if="formData.isUpload">
          <ecm-upload
            :files="formData.defaultFileList"
            :docid="docid"
            @setFile="handleSuccess"
          ></ecm-upload>
        </el-form-item>

        <!-- <el-form-item label="备注" v-if="!formData.isNoRemark">
          <el-input
            type="textarea"
            v-model="formData.remark"
            :rows="3"
          ></el-input>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSure">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, ref, toRefs, watch } from "vue";
import { useRoute } from "vue-router";
import { flowTypeObj } from "./type";
import { getUsersForScience } from "/@/api/user";
import EcmUpload from "/@/components/ecmUpload/index.vue";
import { log } from "console";
export default defineComponent({
  name: "approveDialog",
  components: {
    EcmUpload
  },
  props: {
    visiable: {
      type: Boolean,
      default: true
    },
    flowType: {
      type: String,
      default: "2001"
    },
    nodeId: {
      type: String,
      default: "ACT_010"
    },
    approveRecord: {
      type: Object,
      default: () => {}
    }
  },
  emits: ["sure", "cancel"],
  setup(props, { emit }) {
    const route = useRoute();
    const approveType = route.query.flowType;

    let docid = window["ecmDocType"].project;
    const formDataRef = ref<HTMLFormElement | null>(null) as any;
    const show = ref(props.visiable);
    const endNode =
      props.nodeId === "END" ? props.nodeId.toLocaleUpperCase() : props.nodeId;
    const flowInfo = flowTypeObj[props.flowType][endNode];
    let ids = Object.keys(flowTypeObj[props.flowType]);
    let currentIndex = ids.indexOf(endNode);
    let nextId = "end";
    let nextNode = {
      name: "结束"
    };
    if (!flowInfo.isLast) {
      nextId = ids[currentIndex + 1];
      nextNode = flowTypeObj[props.flowType][nextId];
    }
    const nextJumpToArr = ref(
      flowInfo.nextJumpTo && flowInfo.nextJumpTo.length
        ? flowInfo.nextJumpTo
        : []
    );
    
    const title = ref(flowInfo.name);
    const isMultiple = ref(true)
    let state = reactive({
      formData: {
        currentNodeName: flowInfo.name,
        isSingle: flowInfo.isSingle,
        isUpload: flowInfo.isUpload,
        isFirst: flowInfo.isFirst,
        isLast: flowInfo.isLast,
        nextJumpObj: {
          nextJumpToId:
            flowInfo.nextJumpTo &&
            flowInfo.nextJumpTo[0] &&
            flowInfo.nextJumpTo[0].id,
          name:
            flowInfo.nextJumpTo &&
            flowInfo.nextJumpTo[0] &&
            flowInfo.nextJumpTo[0].name,
          isChargehand:
            flowInfo.nextJumpTo &&
            flowInfo.nextJumpTo[0] &&
            flowInfo.nextJumpTo[0].isChargehand
        },
        nextJumpTo: flowInfo.nextJumpTo,
        nextFlowName: nextNode.name,
        handlederId: null as any,
        isApprove: "1",
        remark: "",
        defaultFileList: [],
        feasibilityreList: [],
        isNoRemark: flowInfo.isNoRemark,
        isNoNextHandler: flowInfo.isNoNextHandler,
        isNoNextApprove: flowInfo.isNoNextApprove
      }
    });

    let userList = ref([]); // 人员列表数据
    let activeNode = ref({}); // 默认下个节点
    let disabledJs = ref(false) // 是否禁用下一步处理人选择
    const formRules = ref({
      handlederId: [
        { required: true, message: "请选择下一步审批人", trigger: "change" }
      ],
      isApprove: [
        { required: true, message: "请确认审批意见", trigger: "change" }
      ]
    });

    onMounted(() => {      
      if(approveType === '3001') {        
        if(state.formData.nextJumpObj.nextJumpToId === 'ACT_020') {
          isMultiple.value = false
        }
        const activeItem = props.approveRecord.find(item => item.nodeName === "研发BP中转")
        activeNode.value = activeItem
        if(nextNode.name === '研发BP中转3' || nextNode.name === '研发BP中转2') {
          const item = {
            companyName: "",
            email: "",
            id: Number(activeItem.assigneeUserId),
            name: activeItem.assignee,
            phoneNum: ""
          }          
          state.formData.handlederId = item
          getUserData(item.name, '')
          disabledJs.value = true
        }
      }
      
      if(approveType === '3001' && flowInfo.id === 'ACT_021') {
        getUserData('', 1)
      }
    })

    const handleSuccess = res => {
      // if (res.code === 200) {
      //   nextTick(() => {
      state.formData.defaultFileList = res.file;
      state.formData.feasibilityreList = res.file;
      //   });
      // }
    };

    const getUserData = async (query = "", type) => {      
      // 金沙审批流委员单独处理
      if (!(approveType === '3001' && (state.formData.nextJumpObj.nextJumpToId === 'ACT_021' || flowInfo.id === 'ACT_021')) && !query) {
        userList.value = [];
        return;
      }
      try {
        let params = {}
        if(approveType === '3001' && (state.formData.nextJumpObj.nextJumpToId === 'ACT_021' || flowInfo.id === 'ACT_021')) {
          params = {
            pageNum: 1,
            pageSize: 200,
            type: type || 1
          };
        } else {
          params = {
            pageNum: 1,
            pageSize: 200,
            name: query,
          };
        }
        const { code, data } = await getUsersForScience(params);
        if (code === 200) {
          userList.value = data.list.map(item => {
            return {
              id: item.id,
              name: item.name + (item.deptName ? "-" + item.deptName : "-无"),
              phoneNum: item.phoneNum,
              email: item.email,
              companyName: item.deptName
            };
          });
          if(approveType === '3001' && (state.formData.nextJumpObj.nextJumpToId === 'ACT_021' || flowInfo.id === 'ACT_021')) {
            state.formData.handlederId = userList.value
          }
        }
      } catch (err) {
        console.log(err);
      }
    };

    const changeHandleder = item => {
      console.log("item", item);
    };

    const handleCancel = () => {
      emit("cancel");
    };

    const handleSure = async () => {
      const isValid = await new Promise(resolve =>
        formDataRef.value.validate(resolve)
      );
      if (isValid) {
        emit("sure", state.formData);
      }
    };

    const changeNextJump = async id => {
      state.formData.nextJumpObj.nextJumpToId = id;
      nextJumpToArr.value.forEach(item => {
        if (item.id === id) {
          state.formData.nextJumpObj.name = item.name;
          state.formData.nextJumpObj.isChargehand = item.isChargehand;
        }
      });
      // 金沙审批流委员单独处理
      if(approveType === '3001' && id === 'ACT_021') {
        getUserData('', 1)
        isMultiple.value = true
      } else if (approveType === '3001' && id === 'ACT_020'){
        isMultiple.value = false
      }
      state.formData.handlederId = []
      userList.value = []
    };

    watch(
      () => props.visiable,
      newVal => {
        show.value = newVal;
      }
    );

    watch(
      () => props.nodeId,
      newVal => {
        if (!newVal) {
          title.value = "发起审批";
        } else {
          title.value = flowTypeObj[props.flowType][newVal];
        }
      }
    );

    watch(
      () => props.flowType,
      newVal => {
        if (newVal) {
          console.log(newVal, "newValnewValnewVal");
        }
      }
    );

    return {
      docid,
      approveType,
      formDataRef,
      formRules,
      title,
      nextJumpToArr,
      ...toRefs(state),
      show,
      userList,
      disabledJs,
      isMultiple,
      getUserData,
      changeHandleder,
      changeNextJump,
      handleCancel,
      handleSure,
      handleSuccess
    };
  }
});
</script>
<style lang="scss" scoped></style>
